package com.jhws.business.card;

import com.jhws.business.card.bo.*;
import com.jhws.business.card.service.ITblCardDimService;
import com.jhws.business.local.bo.LocalConstant;
import com.jhws.business.local.service.LocalService;
import com.jhws.business.owner.bo.TblOwnerDimBo;
import com.jhws.business.owner.service.ITblOwnerDimService;
import com.jhws.core.dataUpdate.service.DataUpdateService;
import com.jhws.core.db.BaseDao;
import com.jhws.util.AccountsUtils;
import com.jhws.util.DateUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

public class TblCardDimServiceSpringImpl implements ITblCardDimService {

    @Resource
    private BaseDao BaseDao;

    @Resource
    private ITblOwnerDimService IOwnerService;

    @Resource
    private DataUpdateService dataUpdateService;
    @Resource
    private LocalService localService;

    @Override
    public List<TblCardPerms> findTblCardsWithTimestamp(String account, Long timeStamp, Boolean IDMode) {
        String where = "where devBuildingNo = '" + account + "'" + (IDMode ? "" : " and enable != 'Y'") + " and timeStamp > '" + timeStamp + "'";
        if (localService.isLanMode()) {
            where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' ";
        }
        return BaseDao.findList("from TblCardPerms " + where);
    }


    /*
     * @ author Alex Tan
     * @ date   2017年1月4日
     * @ 查找符合条件的IC卡列表
     */
    @SuppressWarnings("Duplicates")
    @Override
    public Map<String, Object> findCardList(Map param) {
        String whereClause = new String("1=1 ");

        String ownerName = MapUtils.getString(param, "ownerName", "");
        if (param.containsKey("ownerName") && !ownerName.equals("")) {
            whereClause += "and ownerName like '%" + param.get("ownerName") + "%'";
        }

        String state = MapUtils.getString(param, "state", "");
        if (state != null && StringUtils.isNotEmpty(state)) {
            whereClause += "and state = '" + state + "'";
        }

        String roomInfo = MapUtils.getString(param, "roomInfo", "");
        if (roomInfo != null && StringUtils.isNotEmpty(roomInfo)) {
            if (roomInfo.length() == 4) //如果搜索条件为小区编号长度，则只搜索小区
                whereClause += "and commCode = '" + roomInfo.substring(0, 4) + "'";
            else //如果搜索条件带了房号，则只按房号搜索
                whereClause += "and roomName like '" + roomInfo + "%'";
        }

        String cardType = MapUtils.getString(param, "cardType", "");
        if (cardType != null && StringUtils.isNotEmpty(cardType)) {
            whereClause += "and cardType = '" + cardType + "'";
        }

        if (localService.isLanMode()) {
            whereClause += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' ";
        }

        String hql = "from TblCardDimBo where " + whereClause;

        Map result = BaseDao.queryPage(hql);
        List<TblCardDimBo> list = (List) result.get("list");
        for (TblCardDimBo card : list) {
            if (card.getCardType().equals(CardConstant.CARD_TYPE_NORMAL)) {
                TblOwnerDimBo bo = IOwnerService.findTblOwnerDimById(card.getOwnerCode());
                if (bo != null)
                    card.setRoomName(bo.getRoomInfo());
            } else if (card.getCardType().equals(CardConstant.CARD_TYPE_SUPPER)) {
                if (StringUtils.isEmpty(card.getOwnerName()))
                    card.setOwnerName("管理员");
                card.setRoomName("无");
            }
        }

        return result;
    }

    public void save(TblCardDimBo bo) {
        bo.setIsSynch(LocalConstant.SYNCH_STATE_NO);
        BaseDao.saveOrUpdate(bo);
    }

    public void save(TblCardPerms bo) {
        bo.setIsSynch(LocalConstant.SYNCH_STATE_NO);
        BaseDao.saveOrUpdate(bo);
    }

    public List<TblCardDimBo> findTblCardDimByWhere(String whereClause) throws Exception {
        if (localService.isLanMode()) {
            whereClause += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' ";
        }
        return BaseDao.findList("from TblCardDimBo " + whereClause);
    }

    public TblCardDimBo findTblCardDimById(String CardCode) {
        if (localService.isLanMode()) {
            return BaseDao.get(" from TblCardDimBo where is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' and cardNo='" + CardCode + "'");
        }
        return BaseDao.get(TblCardDimBo.class, CardCode);
    }

    public List<TblCardPerms> findCardPerms(String cardNo) {
        String where = "where cardNo = '" + cardNo + "'";
        if (localService.isLanMode()) {
            where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' ";
        }
        return BaseDao.findList("from TblCardPerms " + where);
    }

    public void removeCardPerms(String cardNo) {
        if (localService.isLanMode()) {
            BaseDao.executeHql("update TblCardPerms set is_synch='" + LocalConstant.SYNCH_STATE_DEL + "' where cardNo='" + cardNo + "'");
        } else {
            BaseDao.deleteByWhere("TblCardPerms", "cardNo = '" + cardNo + "'");
        }
    }

    public void removeCard(String cardNo) {
        if (localService.isLanMode()) {
            BaseDao.executeHql("update TblCardDimBo set is_synch='" + LocalConstant.SYNCH_STATE_DEL + "' where cardNo='" + cardNo + "'");
        } else {
            BaseDao.deleteByWhere("TblCardDimBo", "cardNo = '" + cardNo + "'");
        }
    }

    public void removeCardDevice(Long id) {
        if (localService.isLanMode()) {
            BaseDao.executeHql("update CardDoorDevice set is_synch='" + LocalConstant.SYNCH_STATE_DEL + "' where id='" + id + "'");
        } else {
            BaseDao.delete(CardDoorDevice.class, id);
        }
    }

    @Override
    public TblCardDimBo findCardInfo(String cardNo) {
        String where = "where cardNo = '" + cardNo + "'";
        if (localService.isLanMode()) {
            where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' ";
        }
        // TODO Auto-generated method stub
        List<TblCardDimBo> cList = BaseDao.findList("from TblCardDimBo " + where);
        return cList != null && cList.size() > 0 ? cList.get(0) : null;
    }

    /**
     * 检查IC卡的过期状态，更新所有过期的卡状态和卡权限
     *
     * @throws Exception
     */
    public void updateExpireStateByNow() throws Exception {
        Long nowTimeStamp = System.currentTimeMillis();
        String now = DateUtil.timestamp2StringFmtSec(nowTimeStamp);

        List<String> commCodeList = BaseDao.findList("select distinct  new java.lang.String(commCode) from TblCardDimBo where endDate < '" + now + "' and state != '" + CardConstant.CARD_STATUS_EXPIRE + "'");

        /* 先更新超级卡的时间 */
        BaseDao.executeBySql("update card_info set state = '" + CardConstant.CARD_STATUS_EXPIRE + "',lastModifyTime = '" + now + "',timestamp = '" + nowTimeStamp + "', is_synch='" + LocalConstant.SYNCH_STATE_NO + "' " +
                "where endDate < '" + now + "' and cardType = '" + CardConstant.CARD_TYPE_SUPPER + "' and state != '" + CardConstant.CARD_STATUS_EXPIRE + "'");

        /* 连表更新普通卡时间和普通卡权限时间与状态 */
        BaseDao.executeBySql("update card_info as i,card_perms as p set i.state = '" + CardConstant.CARD_STATUS_EXPIRE + "',i.lastModifyTime = '" + now + "'," +
                "p.enable = '" + CardConstant.CARD_PERM_EXPIRE + "',p.timeStamp = '" + nowTimeStamp + "', p.is_synch='" + LocalConstant.SYNCH_STATE_NO + "', i.is_synch='" + LocalConstant.SYNCH_STATE_NO + "' " +
                "where i.endDate < '" + now + "' and i.cardNo = p.cardNo and p.enable != '" + CardConstant.CARD_PERM_EXPIRE + "'");

        for (String commCode : commCodeList) {
            dataUpdateService.update(nowTimeStamp, CardUpdateData.CARD_PERMS, commCode, false);
        }
    }

    /**
     * 副门禁卡设备相关接口
     */

    public void save(CardDoorDevice device) {
        device.setIsSynch(LocalConstant.SYNCH_STATE_NO);
        BaseDao.saveOrUpdate(device);
    }

    /**
     * 根据条件查找副门禁绑定关系
     *
     * @return
     */
    public List<CardDoorDevice> findCardDoorDevsByWhere(String where) {
        if (localService.isLanMode()) {
            where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' ";
        }
        return BaseDao.findList("from CardDoorDevice where " + where);
    }

    public List<String> findCardDoorDevsBindings(String devNumber) {
        String commCode = AccountsUtils.getCommCode(devNumber);
        String areaName = AccountsUtils.getBuilding(devNumber);
        String unitName = AccountsUtils.getUnit(devNumber);
        String floor = AccountsUtils.getFloor(devNumber);
        String dev = AccountsUtils.getRoom(devNumber);

        String unitStr = commCode + areaName + unitName;
        String device = areaName + unitName + floor + dev;

        String where = "where unit='" + unitStr + "' and device = '" + device + "'";
        if (localService.isLanMode()) {
            where += " and is_synch != '" + LocalConstant.SYNCH_STATE_DEL + "' ";
        }
        return BaseDao.findList("select new java.lang.String(card.cardDeviceNumber) from CardDoorDevice as card " + where);
    }
}
